from django.db.models import Q
from django.contrib.auth import get_user_model
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.status import HTTP_204_NO_CONTENT, HTTP_400_BAD_REQUEST, HTTP_403_FORBIDDEN
from rest_framework.permissions import IsAuthenticated, DjangoModelPermissions
from rest_framework.filters import SearchFilter
from django_filters.rest_framework import DjangoFilterBackend

from workorder.serializers import WorkOrderSerializer
from workorder.models import WorkOrder
from workorder.filter import WorkOrderFilter

User = get_user_model()


class WorkOrderViewset(viewsets.ModelViewSet):
    """
    create: 创建工单
    list: 获取工单列表
    retrieve: 获取工单信息
    update: 更新工单信息
    delete: 删除工单条目
    """

    permission_classes = (IsAuthenticated, DjangoModelPermissions)
    queryset = WorkOrder.objects.all()
    serializer_class = WorkOrderSerializer
    filter_backends = (DjangoFilterBackend, SearchFilter)
    search_fields = ('title', 'id')
    filter_class = WorkOrderFilter
    filter_fields = ('user', )

    ordering_fields = ('id',)

    def filter_daterange(self, queryset):
        """
        过滤创建日期
        日期范围时间参数格式为‘yyyy-M-D,yyyy-M-D’
        """
        daterange = self.request.GET.get('daterange')
        if daterange:
            return queryset.filter(Q(complete_time__range=daterange.split(',')) |
                                   Q(apply_time__range=daterange.split(','))
                                   )
        return queryset

    def get_queryset(self):
        status = self.request.GET.get('status', None)
        # applicant = self.request.user
        # group = applicant.groups.all().values('name')
        # group_name = [r['name'] for r in group]

        user_obj = self.request.user
        if user_obj.is_superuser:  # 管理员返回全部
            queryset = super(WorkOrderViewset, self).get_queryset()
        else:  # 超级和管理身份给他所有组的内容
            queryset = WorkOrder.objects.filter(id=0)  # 取SQL模型一个空的的QuerySet用于后面合并
            for i in user_obj.groups.all():
                queryset = queryset | i.workorder_set.filter()

        # 判断传来的status值判断是申请列表还是历史列表
        if status and int(status) == 1:
            queryset = queryset.filter(status__lte=int(status))
        elif status and int(status) == 2:
            queryset = queryset.filter(status__gte=int(status))
        else:
            pass

        # # 判断登陆用户是否是管理员，是则显示所有工单，否则只显示自己组内的
        # user_obj = self.request.user
        # if user_obj.is_superuser:  # 管理员返回全部
        #     return queryset
        # else:  # 超级和管理身份给他所有组的内容
        #     query_set = WorkOrder.objects.filter(id=0)  # 取SQL模型一个空的的QuerySet用于后面合并
        #     for i in user_obj.groups.all():
        #         query_set = query_set | i.workorder_set.filter()

        # if "ops" not in group_name:
        #     queryset = queryset.filter(applicant=applicant)
        return self.filter_daterange(queryset)

    def check_operation_permissons(self, workorder_obj, change_status):
        """
        操作权限检测
        1. 若非申请人和指派人、超级用户或者没接收工单，不允许放弃
        2. 普通用户若想处理工单，必须在工单指定的组里面，否则不允许处理
        """
        if not self.request.user.is_superuser:
            if change_status == 3:
                if self.request.user.is_superuser not in (workorder_obj.applicant,
                                                          workorder_obj.assign_to,
                                                          workorder_obj.final_processor):
                    return False
            elif change_status == 1:
                if workorder_obj.group not in self.request.user.groups.all():
                    return False
        return True

    def partial_update(self, request, *args, **kwargs):
        """
        工单处理有更新时，将最终处理人改成当前操作表单的用户
        """
        pk = int(kwargs.get("pk"))
        final_processor = self.request.user
        data = request.data
        data['final_processor'] = final_processor
        workorder_obj = WorkOrder.objects.get(id=int(pk))
        change_status = data.get('status')
        if change_status:
            change_status = int(change_status)
            if not self.check_operation_permissons(workorder_obj, change_status):
                return Response(status=HTTP_403_FORBIDDEN)

        try:
            WorkOrder.objects.filter(pk=pk).update(**data)
            # workorder_obj.update(**data)
        except Exception as e:
            print(e)
            return Response(status=HTTP_400_BAD_REQUEST)
        else:
            return Response(status=HTTP_204_NO_CONTENT)
